package com.zoweunion.mechanic.util.task;

import cn.jpush.api.push.PushResult;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.app.PersonalCenterMapper;
import com.zoweunion.mechanic.dao.base.MessageRecordDao;
import com.zoweunion.mechanic.dao.shangji.ShangJiDao;
import com.zoweunion.mechanic.service.base.MessagePushService;
import com.zoweunion.mechanic.util.JiGuangPushUtil;
import com.zoweunion.mechanic.util.UuidUtil;
import com.zoweunion.mechanic.util.constants.PushConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static com.zoweunion.mechanic.util.FunUtil.logger;

/**
 * 定时任务
 * @author rentianfeng
 */
@Component
public class MessagePushScheduleTask extends BaseController {
    @Autowired
    private MessagePushService messagePushService;
    @Autowired
    private PersonalCenterMapper personalCenterMapper;
    @Autowired
    private JiGuangPushUtil jiGuangPushUtil;
    @Autowired
    private MessageRecordDao messageRecordDao;
    @Autowired
    private ShangJiDao shangJiDao;

    /**
     * 每10分钟执行一次
     */
    // @Scheduled(cron = "0 0/10 * * * ? ")
    private void configureTasks() {
        logBefore(logger,"开启消息推送定时任务");
        messagePushService.deMessagePush();
        logAfter(logger);
    }

    /**
     * 每日十点当有人浏览/转发，出租/出售/求租/求购详情时，推送给出租/出售/求租/求购的发布者
     */
    //测试一分钟发一次
   // @Scheduled(cron = "0 * * * * ?")
    @Scheduled(cron = "0 0 10 * * ?")
    private  void   pushTask() {


        List<Map<String, Object>> receiveUserList = personalCenterMapper.getReceiveUsers();
        Map<Integer, List<Map<String, Object>>> sendTypeToReceiveUsers = new HashMap<>();

        for (Map<String, Object> receiveUserMap : receiveUserList) {
            Integer sendType = (Integer) receiveUserMap.get("send_type");
            String receiveUser = (String) receiveUserMap.get("receive_user");
            Long  totalCount = (Long ) receiveUserMap.get("total_count");
            // 检查是否已经存在以 sendType 为键的列表，如果不存在则创建一个新的列表
            List<Map<String, Object>> userList = sendTypeToReceiveUsers.get(sendType);
            if (userList == null) {
                userList = new ArrayList<>();
                sendTypeToReceiveUsers.put(sendType, userList);
            }
            List<Map<String,Object>> visitList = personalCenterMapper.getVisit(receiveUserMap);
            Set<String> uniqueContexts = new HashSet<>();
            // 用于存储不重复的context值
            List<String> uniqueContextList = new ArrayList<>();

            for (Map<String, Object> visit : visitList) {
                String context = (String) visit.get("context");

                // 检查context是否已经存在于uniqueContexts中
                if (!uniqueContexts.contains(context)) {
                    uniqueContexts.add(context); // 将context添加到uniqueContexts中
                    uniqueContextList.add(context); // 将不重复的context添加到uniqueContextList中
                }
            }
            // 在这里编写发送消息的逻辑
            logger.info("十点发送消息");
            // 浏览
            int accessCount=personalCenterMapper.getAccessCount(receiveUserMap);
            //收藏
            int favoriteCount=personalCenterMapper.getFavoriteCount(receiveUserMap);
            //转发
            int forwardCount=personalCenterMapper.getForwardCount(receiveUserMap);
            Map<String, Object> messageMap = new HashMap<>();
            AtomicInteger outcome = new AtomicInteger();
            if (accessCount != 0 || favoriteCount != 0 || forwardCount != 0) {
                for (String context : uniqueContextList) {
                    //APP推送消息
                    messageMap.put("push_user_id",receiveUserMap.get("receive_user"));
                    messageMap.put("title", "浏览信息");
                    messageMap.put("push_content", "您发布的"+context+"信息昨日被浏览"+accessCount+"次，被收藏"+favoriteCount+"次，"+"被转发"+forwardCount+"次，点此查看详情>>>");
                    messageMap.put("create_user",receiveUserMap.get("receive_user"));
                    //messageMap.put("push_user_id","bbc9aa19387b49f2a6103d402b7803ef");
                    PushResult pushResultresult =jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.TITLE_NEWOROLD_MACHINE_BROSE_WARNING, "", UuidUtil.get32UUID());
                    //保存到数据库中
                    outcome.addAndGet(pushResultresult == null ? 1 : 0);
                    if(pushResultresult != null && pushResultresult.statusCode == 0) {
                        receiveUserMap.put("id", UuidUtil.get32UUID());
                        receiveUserMap.put("user", receiveUserMap.get("receive_user"));
                        receiveUserMap.put("s_id", receiveUserMap.get("s_id"));
                        //send_type=400,当有人浏览/转发的type
                        receiveUserMap.put("send_type", 400);
                        receiveUserMap.put("receive_user", receiveUserMap.get("receive_user"));
                        receiveUserMap.put("client", "YD");
                        receiveUserMap.put("context", messageMap.get("push_content"));
                        receiveUserMap.put("extra_params", "{\"push_tuisong\":\"" + receiveUserMap.get("id").toString() + "\"}");
                        messageRecordDao.addMessageRecord(receiveUserMap);
                        // 更新是否推送的标识F
                        shangJiDao.updateZoweBuyinfoDetailForPushFlag(receiveUserMap);
                    }
                }

            }

        }

    }
}
